﻿using System;
using System.Linq;
using System.Web.Mvc;
using EmitMapper;
using EmitMapper.MappingConfiguration;
using PCE.Data;
using PCE.Data.Queries;
using PCE.Domain;
using PCE.Mvc.Binders;
using PCE.Mvc.Extensions;
using PCE.Mvc.Filters;
using PCE.Mvc.Model;

namespace PCE.Mvc.Controllers
{
	public class TenderController : Controller
	{
		private static readonly ObjectsMapper<Tender, TenderDetails> Mapper = 
			ObjectMapperManager
			.DefaultInstance
			.GetMapper<Tender, TenderDetails>(
				new DefaultMapConfig()
					.ConvertUsing<DateTime, string>(d => d.ToShortDateString())
					.ConvertUsing<ProductionSphere, string>(s => s.GetDescription())
					.ConvertUsing<bool, string>(b => b ? "Да" : "Нет")
			);

		private static readonly ObjectsMapper<TenderDetails, Tender> MapperInverse =
			ObjectMapperManager
				.DefaultInstance
				.GetMapper<TenderDetails, Tender>(
				//new DefaultMapConfig()
				//    .ConvertUsing<DateTime, string>(d => d.ToShortDateString())
				//    .ConvertUsing<ProductionSphere, string>(s => s.GetDescription())
				//    .ConvertUsing<bool, string>(b => b ? "Да" : "Нет")
			);
		
		private readonly IRepository<Tender, int> _tenderRepository;

		private readonly IRepository<Customer, int> _customerRepository;

		public TenderController(IRepository<Tender, int> tenderRepository, IRepository<Customer, int> customerRepository)
		{
			_tenderRepository = tenderRepository;
			_customerRepository = customerRepository;
		}

		[HttpGet]
		[PersistanceRequired]
		public ActionResult List([CustomerIdentityBinder] int customerId)
		{
			var orders = _tenderRepository.FindAll(TenderSpecs.OfCustomer(customerId));

			return View(orders.Select(Mapper.Map));
		}

		[HttpGet]
		public ActionResult Create()
		{
			return View("Edit");
		}

		[HttpGet]
		[PersistanceRequired]
		public ActionResult Edit([CustomerIdentityBinder] int customerId, int tenderId)
		{
			Tender tender;
			
			if (tenderId == default(int) || (tender = _tenderRepository.Find(TenderSpecs.OfCustomer(customerId, tenderId))) == null)
				return new HttpNotFoundResult();

			return View(Mapper.Map(tender));
		}

		[HttpPost]
		[PersistanceRequired]
		public ActionResult Save([CustomerIdentityBinder] int customerId, TenderDetails details)
		{
			var customer = _customerRepository.Get(customerId);

			var tender = MapperInverse.Map(details);

			if (tender.Id == 0)
				customer.AddTender(tender);
			else
				customer.UpdateTender(tender);

			_customerRepository.Save(customer);
			
			return View("Edit", details);
		}

		public ActionResult Details(int customerId, int id)
		{
			throw new NotImplementedException();
		}

		
	}
}